package com.dmzapp.api.servlet;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.dmzapp.api.cache.local.LocalCache;
import com.dmzapp.api.cache.redis.MiddleRedisServer;
import com.dmzapp.api.cache.redis.RedisClient;
import com.dmzapp.api.db.AppDao;
import com.dmzapp.api.service.RedisAndDBService;
import com.dmzapp.api.vo.IncomeRecord;
import com.dmzapp.api.vo.UserAccount;

/**
 * 
 * 判断是否是有效地安装，如果是的话，添加新的安装记录 Servlet implementation class for Servlet:
 * InstallCheckRequestHandler
 * 
 */
public class InstallCheckRequestHandler extends DMZSerlvet implements javax.servlet.Servlet {
    static final long serialVersionUID = 1L;
    private ObjectMapper mapper = new ObjectMapper();

    /**
     * 1. 验证身份，看username对应的deviceid跟mac地址是否匹配 
     * 2. 验证是否已经在服务器已经有过安装该app的记录 
     * 3. 验证当前app是否还有余额 
     * 4. 都验证无误后，插入新的income记录
     */
    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response) {
        String deviceid = request.getParameter("d");
//        String macAddress = request.getParameter("m");
        String ip = (String) request.getAttribute("i");
        String username = (String) request.getAttribute("u");
        String packagename = request.getParameter("p");

        /**
         * 具体步骤： 
         * 1. 查看线程非安全的从redis中查看username是否存在 
         * 2. 如果存在则验证跟client端传过来的mac，deviceid是否匹配 
         * 3. 如果不存在则从db中获取username对应的信息，再做验证，并将信息set到redis中 
         * 4. 如果验证成功，则查看username对应installpackagelist中是否存在传过来的packagename 
         * 5. 首先从redis中获取（非线程安全），没有的话从数据库取（再写入redis中） 
         * 6. 验证当前app是否还有余额 
         * 7. 最后验证都无误后，插入新的income记录，并将packagename写入redis对应key的set中
         */
        
        UserAccount useraccount = RedisClient.getInstance().checkUserExist(username);
        if (useraccount == null) {
            useraccount = AppDao.getInstance().getUserInfo(username);
            if (useraccount != null) {
                RedisClient.getInstance().setUseraccount(useraccount);
            }
        }

        boolean flg = false;
        if (useraccount != null && deviceid.equals(useraccount.getDeviceid())) {
            
            Collection<String> installedPackages = RedisClient.getInstance().checkInstallpackagesExist(username);
            
            // packages 不存在，有可能是缓存中没有该用户的数据，再去数据库中获取一把
            if (installedPackages == null || installedPackages.isEmpty()) {
                installedPackages = AppDao.getInstance().getInstallPackalistByusername(username);

            }
            boolean effectiveRecord = false;
            
            if(LocalCache.getInstance().appCache.get(packagename) == null) {
                return;
            }
            
            String enduserIncome = String.valueOf(LocalCache.getInstance().appCache.get(packagename).getDownloadFee());
            if (installedPackages != null) {
                RedisClient.getInstance().setInstallpackages(username, installedPackages);
                //TODO: 隐患!要不要在redis中存放全局实时的bid数据，在广告主修改bid后及时生效
                
                if (installedPackages.contains(packagename)) {
                    // 无效的安装

                } else if (MiddleRedisServer.getInstance().checkAndChangeAppRestMoney(packagename, enduserIncome)) {
                    // 该package不在用户已安装过的list中
                    effectiveRecord = true;
                }
                
            } else if (MiddleRedisServer.getInstance().checkAndChangeAppRestMoney(packagename, enduserIncome)) {
                //还没有该用户的任何package，
                effectiveRecord = true;
            }
            
            if (effectiveRecord) {
                IncomeRecord incomeRecord = new IncomeRecord();
                incomeRecord.setDeviceid(deviceid);
                incomeRecord.setIncome(enduserIncome);
                incomeRecord.setIp(ip);
                incomeRecord.setPackagename(packagename);
                incomeRecord.setServiceid(1);
                incomeRecord.setUsername(username);
                incomeRecord.setCreate_time(new Date());
                
                // 计算该用户的余额
                RedisAndDBService.addUserRestAndAmount(username, enduserIncome);

                // 记录用户的收入信息
                RedisAndDBService.inserIncomeDetail(incomeRecord);
                
                // 单独用redis服务记录用户的安装applist
                RedisClient.getInstance().addInstallpackageForuser(username, packagename);

                flg = true;
            }
        }
        Map<String, Object> responseMap = new HashMap<String, Object>();
        responseMap.put("amount", RedisAndDBService.getUserAmount(username));
        responseMap.put("rest", RedisAndDBService.getUserRest(username));
        responseMap.put("server_time", Calendar.getInstance().getTimeInMillis());
        if (flg) {
            responseMap.put("status", "200");
            responseMap.put("msg", "恭喜您，获得安装应用奖励");
        } else {
            responseMap.put("status", "500");
            responseMap.put("msg", "审核失败");
        }
        try {
            mapper.writeValue(response.getWriter(), responseMap);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}